package org.ns.example.interceptor;

import com.alibaba.fastjson.JSON;
import org.ns.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
// 登陆拦截器
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            if (handlerMethod.hasMethodAnnotation(LoginVerify.class)) {
                if (!userService.isLogin(request)) {
                    // 如果没有登陆 判断是API还是页面
                    try {
                        if (handlerMethod.hasMethodAnnotation(ResponseBody.class)) {
                            response.setContentType("application/json;charset=UTF-8");
                            PrintWriter out = response.getWriter();
                            out.write(JSON.toJSONString(userService.getNotLoginResponse()));
                        } else {
                            response.sendRedirect("/"); // 页面进行重定向
                        }
                        return false;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return true;
    }

}
